package Text;

public class MoneyLast {
    volatile boolean take = false;//提供同步的变量设置
    Object flag = new Object();
    private int money = 1000;
    int i = 2000;
    int j = 100;
    Thread Aq = new Thread(()->{
        while (money>0){
            if (!take){
                synchronized (flag){
                    try {
                        System.out.println(Thread.currentThread().getName()+"从柜台取走了"+j+"元,还剩"+(money-j)+"元");
                        money-=j;
                        flag.wait(100);//阻塞
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
            }else {
                take = false;
            }
        }
    });
    Thread Bq = new Thread(()->{
        while (money>0){
            if (!take){
                synchronized (flag){
                    try {
                        System.out.println(Thread.currentThread().getName()+"从ATM取走了"+j+"元,还剩"+(money-j)+"元");
                        money-=j;
                        flag.wait(100);//阻塞
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
            }else {
                take = false;
            }
        }
    });

    Thread Cc = new Thread(()->{
        while (true){
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            take = true;
            money+=i;
            System.out.println(Thread.currentThread().getName()+"存了"+i+"元,还剩"+money+"元");
            synchronized (flag){
                flag.notify();//唤醒
            }

        }
    });

    public static void main(String[] args) {
        MoneyLast moneyLast = new MoneyLast();
        moneyLast.Aq.setName("A");
        moneyLast.Bq.setName("B");
        moneyLast.Cc.setName("C");
        moneyLast.Aq.start();
        moneyLast.Bq.start();
        moneyLast.Cc.start();
    }
}